package com.qmx.launcher.activity.general;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import android.widget.Toast;

import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.utils.Utils;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.qmx.launcher.R;
import com.qmx.launcher.activity.base.BaseActivity;
import com.qmx.launcher.view.CommomDialog;
import com.qmx.launcher.view.CustomerOnOff;

import java.io.IOException;

public class GeneralTActivity extends BaseActivity implements View.OnClickListener {

    MainUpView mainUpView1;
    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus; // 4.3以下版本需要自己保存.

    public int requestCode = 0;
    private TextView tv_terminal_name;
    private TextView tv_server;
    private CustomerOnOff custom_onoff, custom_self_inspection;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_general_t);

        tv_terminal_name = (TextView) findViewById(R.id.tv_terminal_name);
        tv_server = (TextView) findViewById(R.id.tv_server);
        /* MainUpView 设置. */
        mainUpView1 = (MainUpView) findViewById(R.id.mainUpView1);
        mOpenEffectBridge = (OpenEffectBridge) mainUpView1.getEffectBridge();
        if (Utils.getSDKVersion() == 17) { // 测试 android 4.2版本.
            switchNoDrawBridgeVersion();
        } else { // 其它版本（android 4.3以上）.
            mainUpView1.setUpRectResource(R.drawable.blue_arrow); // 设置移动边框的图片.
            //            mainUpView1.setShadowResource(R.drawable.item_shadow); // 设置移动边框的阴影.
        }
        // mainUpView1.setUpRectResource(R.drawable.item_highlight); //
        // 设置移动边框的图片.(test)
        // mainUpView1.setDrawUpRectPadding(new Rect(0, 0, 0, -26)); //
        // 设置移动边框的距离.
        // mainUpView1.setDrawShadowPadding(0); // 阴影图片设置距离.
        // mOpenEffectBridge.setTranDurAnimTime(500); // 动画时间.

        FrameMainLayout main_lay11 = (FrameMainLayout) findViewById(R.id.main_lay);
        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {
                if (newFocus != null)
                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                float scale = 1;
                mainUpView1.setFocusView(newFocus, mOldFocus, scale);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
                if (newFocus != null) {
                    testTopDemo(newFocus, scale);
                }
            }
        });
        findViewById(R.id.rv_terminal_name).setOnClickListener(this);
        findViewById(R.id.rv_terminal).setOnClickListener(this);
        findViewById(R.id.rv_server).setOnClickListener(this);
        findViewById(R.id.rv_voices).setOnClickListener(this);
        findViewById(R.id.rv_touch_screen).setOnClickListener(this);
        findViewById(R.id.rv_self_inspection).setOnClickListener(this);
        findViewById(R.id.rv_screensaver).setOnClickListener(this);
        findViewById(R.id.rv_dormancy_state).setOnClickListener(this);
        findViewById(R.id.rv_shutdown).setOnClickListener(this);

        custom_onoff = (CustomerOnOff) findViewById(R.id.custom_onoff);

        custom_onoff.setOnClickListener(new CustomerOnOff.onClickListener() {
            @Override
            public void onLeftRowClick() {
                Toast.makeText(GeneralTActivity.this, "点击关箭头", Toast.LENGTH_SHORT).show();
                custom_onoff.stateChange("关");
            }

            @Override
            public void onRightRowClick() {
                Toast.makeText(GeneralTActivity.this, "onRightRowClick点击开箭头", Toast.LENGTH_SHORT).show();
                custom_onoff.stateChange("开");
            }
        });
        //        findViewById(R.id.custom_self_inspection).setOnClickListener(this);

        /**
         * 尽量不要使用鼠标. !!!! 如果使用鼠标，自己要处理好焦点问题.(警告)
         */
        //		main_lay11.setOnHoverListener(new OnHoverListener() {
        //			@Override
        //			public boolean onHover(View v, MotionEvent event) {
        //				mainUpView1.setVisibility(View.INVISIBLE);
        //				return true;
        //			}
        //		});
        //
        for (int i = 0; i < main_lay11.getChildCount(); i++) {
            main_lay11.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        //						v.performClick();
                        v.requestFocus();
                    }
                    return false;
                }
            });
        }
    }

    public View gridview_lay;

    /**
     * 这是一个测试DEMO，希望对API了解下再使用. 这种DEMO是为了实现这个效果:
     * https://raw.githubusercontent.com/FrozenFreeFall/ImageSaveHttp/master/
     * chaochupingm%20.jpg
     */
    public void testTopDemo(View newView, float scale) {
        // 测试第一个小人放大的效果.
        //        if (newView.getId() == R.id.gridview_lay) { // 小人在外面的测试.
        RectF rectf = new RectF(getDimension(R.dimen.w_7), getDimension(R.dimen.h_7), getDimension(R.dimen.w_7),
                getDimension(R.dimen.h_7));
        mOpenEffectBridge.setDrawUpRectPadding(rectf); // 设置移动边框间距，不要被挡住了。
        mOpenEffectBridge.setDrawShadowRectPadding(rectf); // 设置阴影边框间距，不要被挡住了。
        mOpenEffectBridge.setDrawUpRectEnabled(false); // 让移动边框绘制在小人的下面.
        //            test_top_iv.animate().scaleX(scale).scaleY(scale).setDuration(100).start(); // 让小人超出控件.
        //        } else { // 其它的还原.
        //        mOpenEffectBridge.setDrawUpRectPadding(0);
        //        mOpenEffectBridge.setDrawShadowPadding(0);
        //        mOpenEffectBridge.setDrawUpRectEnabled(true);
        //            test_top_iv.animate().scaleX(1.0f).scaleY(1.0f).setDuration(100).start(); // 让小人超出控件.
        //        }
    }

    public float getDimension(int id) {
        return getResources().getDimension(id);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rv_terminal_name:
                showMsg("rv_terminal_name demo test");
                startActivityForResult(new Intent(getApplicationContext(), TerminalActivity.class), requestCode);
                break;
            case R.id.custom_onoff:
                showMsg("custom_onoff demo test");
                //                startActivity(new Intent(getApplicationContext(), TerminalActivity.class));
                break;
            case R.id.rv_server:
                showMsg("rv_server test");
                requestCode = 1;
                startActivityForResult(new Intent(getApplicationContext(), ServerAddressActivity.class), requestCode);
                break;
            case R.id.rv_voices:
                showMsg("rv_voices");
                requestCode = 4;
                startActivityForResult(new Intent(getApplicationContext(), LanguageActivity.class), requestCode);
                break;
            case R.id.rv_touch_screen:
                showMsg("rv_touch_screen");
                //                switchNoDrawBridgeVersion();
                break;
            case R.id.custom_self_inspection:
                showMsg("rv_self_inspection");
                //                startActivity(new Intent(getApplicationContext(), TerminalActivity.class));
                break;
            case R.id.rv_screensaver:
                showMsg("rv_screensaver");
                requestCode = 2;
                startActivityForResult(new Intent(getApplicationContext(), SleepOrScreenActivity.class), requestCode);
                break;
            case R.id.rv_dormancy_state:
                showMsg("rv_dormancy_state");
                requestCode = 3;
                startActivityForResult(new Intent(getApplicationContext(), SleepOrScreenActivity.class), requestCode);
                break;
            case R.id.rv_shutdown:
                showMsg("rv_shutdown");
                mDialog();
                //                reboot();
                //                startActivity(new Intent(getApplicationContext(), TerminalActivity.class));
                break;
            default:
                break;
        }
    }


    public void mDialog() {
        //弹出提示框
        new CommomDialog(this, R.style.dialog, "您确定关机或者重启？", "关机", "重启", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    //                    Toast.makeText(GeneralTActivity.this, "确定", Toast.LENGTH_SHORT).show();
                    shutdown();
                    dialog.dismiss();
                } else {
                    //                    Toast.makeText(GeneralTActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    reboot();
                    dialog.dismiss();
                }

            }
        }).setTitle("提示").show();
    }

    /**
     * 重启
     *
     * @return
     */
    public static int reboot() {
        int r = 0;
        try {
            Process process = Runtime.getRuntime().exec("su -c reboot");
            r = process.waitFor();

        } catch (IOException e) {
            e.printStackTrace();
            r = -1;
        } catch (InterruptedException e) {
            e.printStackTrace();
            r = -1;
        }
        Log.i("info", "time: " + r);
        return r;
    }

    /**
     * 关机
     *
     * @return
     */
    public static int shutdown() {
        int r = 0;
        try {
            Process process = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});
            r = process.waitFor();
            java.lang.System.out.println("r:" + r);
        } catch (IOException e) {
            e.printStackTrace();
            r = -1;
        } catch (InterruptedException e) {
            e.printStackTrace();
            r = -1;
        }
        return r;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //        System.out.println("测试数据=" + data.getStringExtra("ed_terminal_name"));
        switch (requestCode) {
            case 0:
                tv_terminal_name.setText(data.getStringExtra("ed_terminal_name"));
                break;
            case 1:
                if (data != null) {
                    tv_server.setText(data.getStringExtra("tv_server"));
                }
                break;
            case 2:
                showMsg("rv_about22222");
                //                tv_terminal_name.setText(data.getStringExtra("ed_terminal_name"));
                break;
            case 3:
                showMsg("rv_about33333");
                //                tv_terminal_name.setText(data.getStringExtra("ed_terminal_name"));
                break;
            case 4:
                showMsg("LanguageActivity");
                //                tv_terminal_name.setText(data.getStringExtra("ed_terminal_name"));
                break;
            default:
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showMsg(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    private void switchNoDrawBridgeVersion() {
        float density = getResources().getDisplayMetrics().density;
        RectF rectf = new RectF(getDimension(R.dimen.w_10) * density, getDimension(R.dimen.h_10) * density,
                getDimension(R.dimen.w_9) * density, getDimension(R.dimen.h_9) * density);
        EffectNoDrawBridge effectNoDrawBridge = new EffectNoDrawBridge();
        effectNoDrawBridge.setTranDurAnimTime(200);
        //        effectNoDrawBridge.setDrawUpRectPadding(rectf);
        mainUpView1.setEffectBridge(effectNoDrawBridge); // 4.3以下版本边框移动.
        mainUpView1.setUpRectResource(R.drawable.white_light_10); // 设置移动边框的图片.
        mainUpView1.setDrawUpRectPadding(rectf); // 边框图片设置间距.


    }


}
